/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */
package com.jav;

import com.jav.bean.Capturas;
import com.jav.bean.Producto;
import com.jav.data.InvMovilData;
import com.jav.per.PersisCaptura;
import com.jav.per.PersisSetup;
import com.jav.per.Persistencia;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextField;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.GridLayout;
import com.sun.lwuit.util.Resources;
import java.util.Enumeration;
import java.util.Vector;

public class CapturaForm extends Form {

    private Button bt_producto;
    private Button bt_des = createButton();
    private Button bt_footer;
    private Label lb_precio = new Label("");
    private Label lb_TotPacas = new Label("");
    private Label lb_TotUnidades = new Label("");
    private com.jav.componentes.textfield.TextField tf_pacas = new com.jav.componentes.textfield.TextField("");    
    private com.jav.componentes.textfield.TextField tf_unidades = new com.jav.componentes.textfield.TextField("");    
    
    private Producto prodSelect;
    private Button bt_addCar;
    private Image imgError;
    private static final VentanaEspera waiting = new VentanaEspera("CARGANDO...");
    private Vector capturas = new Vector(0);
    private boolean permisoVista;

    public CapturaForm() {
        super("CAPTURA");
        Resources res = null;
        try {

            setLayout(new BoxLayout(BoxLayout.Y_AXIS));
            setTransitionInAnimator(Transition3D.createCube(500, true));
            setTransitionOutAnimator(Transition3D.createCube(500, false));
            res = Datos.getInstance().getRes();
            imgError = res.getImage("cancel.png");

            if (Datos.getInstance().isVacioPro()) {

                Command okCommand = new Command("OK");
                Dialog.show("Falló!", "Debe cargar los datos de los productos previamente!",
                        okCommand, new Command[]{okCommand}, Dialog.TYPE_INFO, imgError, 0, null);

                addCommand(new Command("Atrás", res.getImage("bck.png")) {

                    public void actionPerformed(ActionEvent evt) {

                        new Thread(new Runnable() {

                            public void run() {
                                waiting.showModeless();
                                capturas = null;
                                Form form = InvMovilMidlet.getMainForm();
                                waiting.dispose();
                                form.show();
                            }
                        }).start();

                    }
                });
                return;

            }


            tf_pacas.setConstraint(TextField.NUMERIC);
            tf_unidades.setConstraint(TextField.NUMERIC);
            tf_pacas.setInputModeOrder(new String[]{"123"});
            tf_pacas.setUseSoftkeys(false);
            
            tf_unidades.setInputModeOrder(new String[]{"123"});
            tf_unidades.setUseSoftkeys(false);





            bt_producto = new Button("(+)Producto", res.getImage("adBrowser.png"));
            bt_producto.setFocusable(true);
            bt_producto.setAlignment(CENTER);
            bt_producto.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    ProductosDialog.getInstance().show();
                    prodSelect = ProductosDialog.proselect;
                    if (prodSelect != null) {
                        bt_des.setText(prodSelect.getDescripcion());
                        lb_precio.setText("$ " + prodSelect.getPrecio());
                        tf_pacas.requestFocus();
                    } else {
                        bt_des.setText("");
                        lb_precio.setText("");
                        bt_producto.requestFocus();
                    }

                }
            });

            bt_addCar = new Button("Agregar", res.getImage("car"));
            bt_addCar.setAlignment(CENTER);

            bt_addCar.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    if (prodSelect != null) {
                        int pacas = 0;
                        int unidades = 0;
                        try {
                            pacas = Integer.parseInt(tf_pacas.getText());
                        } catch (Exception e) {
                            pacas = 0;
                        }
                        try {
                            unidades = Integer.parseInt(tf_unidades.getText());
                        } catch (Exception e) {
                            unidades = 0;
                        }

                        if ((pacas >= 0 || unidades >= 0) && (pacas + unidades > 0)) {

                            Capturas c = new Capturas();
                            c.setPacas(pacas);
                            c.setUnidades(unidades);
                            c.setProducto(prodSelect);
                            capturas.addElement(c);
                            upadte();
                            prodSelect = null;
                            tf_pacas.setText("");
                            tf_unidades.setText("");
                            bt_des.setText("");
                            lb_precio.setText("");
                            bt_producto.requestFocus();

                        }


                    } else {
                        Command okCommand = new Command("OK");
                        Dialog.show("ERROR", "Debe adicionar primero un producto",
                                okCommand, new Command[]{okCommand}, Dialog.TYPE_INFO, imgError, 0, null);
                    }
                }
            });


            addComponent(bt_producto);
            Container largest = createPair("Des: ", bt_des, 30);
            int largestW = largest.getComponentAt(0).getPreferredW();

            addComponent(createPair("Pacas: ", tf_pacas, largestW));
            addComponent(createPair("Unds.: ", tf_unidades, largestW));
            addComponent(bt_addCar);
            addComponent(largest);
            addComponent(createPair("Precio: ", lb_precio, largestW));

            PersisSetup pd = Datos.getInstance().getPersisSetup();
            if (pd != null) {
                this.permisoVista = pd.PermisoVistaValores();
            }

            if (this.permisoVista) {
                addComponent(createPair("$ TOT_P: $", lb_TotPacas, largestW));
                addComponent(createPair("$ TOT_U: $", lb_TotUnidades, largestW));
            }




            addCommand(new Command("Guardar", res.getImage("download_cover.png")) {

                public void actionPerformed(ActionEvent evt) {
                    if (capturas != null && !capturas.isEmpty()) {


                        new Thread(new Runnable() {

                            public void run() {

                                removeAllCommands();
                                try {
                                    int consecutivo = Datos.getInstance().getMaxPedido();
                                    Enumeration e = capturas.elements();
                                    while (e.hasMoreElements()) {
                                        Capturas cap = (Capturas) e.nextElement();
                                        PersisCaptura pp = new PersisCaptura();
                                        pp.setConsecutivo(consecutivo);
                                        pp.setCodigoProducto(cap.getProducto().getCodigo());
                                        pp.setCodProveedor(cap.getProducto().getProveedor());
                                        pp.setUnidadesXpaca(cap.getProducto().getPacas());
                                        pp.setPacas(cap.getPacas());
                                        pp.setUnidades(cap.getUnidades());
                                        pp.setPrecio(cap.getProducto().getPrecio());

                                        Persistencia p = new Persistencia(InvMovilData.PERS_CAPTURA);
                                        p.save(pp.persist());
                                    }
                                    Datos.getInstance().setMaxPedido(consecutivo);

                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }

                                waiting.showModeless();
                                capturas = null;
                                Form form = InvMovilMidlet.getMainForm();
                                waiting.dispose();
                                form.show();
                            }
                        }).start();

                    }
                }
            });

            addCommand(new Command("Atrás", res.getImage("bck.png")) {

                public void actionPerformed(ActionEvent evt) {
                    if (Dialog.show("¿?", "AL REGRESAR SE PERDERÁN LOS DATOS DE LA CAPTURA.\nDESEA CONTINUAR?", "SI", "NO")) {
                        new Thread(new Runnable() {

                            public void run() {
                                waiting.showModeless();
                                capturas = null;
                                Form form = InvMovilMidlet.getMainForm();
                                waiting.dispose();
                                form.show();
                            }
                        }).start();

                    }
                }
            });

            addCommand(new Command("add..Producto", res.getImage("add.png")) {

                public void actionPerformed(ActionEvent evt) {

                    ProductoDialog pro = new ProductoDialog();
                    pro.show();
                    prodSelect = pro.getPro_select();
                    if (prodSelect != null) {
                        bt_des.setText(prodSelect.getDescripcion());
                        lb_precio.setText("$ " + prodSelect.getPrecio());
                        tf_pacas.requestFocus();
                    } else {
                        bt_des.setText("");
                        lb_precio.setText("");
                        bt_producto.requestFocus();
                    }
                }
            });

            addCommand(new Command("Consultar", res.getImage("adBrowser.png")) {

                public void actionPerformed(ActionEvent evt) {
                    if (capturas != null && !capturas.isEmpty()) {
                        new Thread(new Runnable() {

                            public void run() {
                                new ConsultaCapturaDialog(capturas).show();
                                eliminarCapturas();
                                upadte();
                            }

                            private void eliminarCapturas() {
                                try {
                                    if (!capturas.isEmpty()) {
                                        Enumeration e = capturas.elements();
                                        while (e.hasMoreElements()) {
                                            Capturas pro = (Capturas) e.nextElement();
                                            if (pro.isEliminar()) {
                                                capturas.removeElement(pro);
                                            }
                                        }
                                    }

                                } catch (Exception e) {
                                }

                            }
                        }).start();
                    }

                }
            });

            bt_footer = new Button("");
            bt_footer.setHeight(bt_producto.getHeight()/2);
            addComponent(bt_footer);



        } catch (Exception e) {
            Datos.getInstance().addLogs(e.getMessage());
        } finally {
            res = null;
        }
    }

    protected Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label l = new Label(label);
        Dimension d = l.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), minWidth));
        l.setPreferredSize(d);
        //l.getStyle().setBgTransparency(100);
        pair.addComponent(BorderLayout.WEST, l);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

    protected Container createSub(Component c, Component c2) {
        Container pair = new Container(new GridLayout(1, 2));
        Container pair2 = new Container(new BorderLayout());
        Container pair3 = new Container(new BorderLayout());
        pair2.addComponent(BorderLayout.CENTER, c);
        pair3.addComponent(BorderLayout.CENTER, c2);
        pair.addComponent(pair2);
        pair.addComponent(pair3);
        return pair;
    }

    private Button createButton() {
        Button boton = new Button("") {

            public void startTicker(long delay, boolean rightToLeft) {
                super.startTicker(100, true);
            }
        };

        return boton;
    }

    private void upadte() {

        if (this.permisoVista) {
            float totalPacas = 0;
            float totalUnidades = 0;
            if (capturas != null && !capturas.isEmpty()) {


                for (int i = 0; i < capturas.size(); i++) {
                    Capturas c = (Capturas) capturas.elementAt(i);
                    totalPacas += c.getPacas() * (c.getProducto().getPacas()) * (c.getProducto().getPrecio());
                    totalUnidades += c.getUnidades() * (c.getProducto().getPrecio());
                }


            }
            lb_TotPacas.setText(Float.toString(totalPacas));
            lb_TotUnidades.setText(Float.toString(totalUnidades));
            repaint();
        }


    }
}
